<template>
  <div class="params">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert class="warning" title="注意：只允许为第三级分类设置相关参数！" show-icon type="warning"></el-alert>
      <div class="params">
        <span style="padding:0 10px">商品分类 :</span>
        <el-cascader
          v-model="params"
          :options="goodsCateData"
          :props="cateProps"
          @change="changeGoodsCate"
        ></el-cascader>
      </div>
      <el-tabs v-model="activeCate" @tab-click="tabParams">
        <el-tab-pane label="动态参数" name="params">
          <el-button :disabled="isBtnDisabled" @click="addParamBtn" type="primary">添加参数</el-button>
          <el-table stripe :data="paramsData" border style="width: 100%">
            <el-table-column type="expand" width="50" class="expand">
              <template v-slot="scope">
                <el-tag
                  class="paramClass"
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="paramInputVisible"
                  v-model="paramInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="paramInputConfirm(scope.row)"
                  @blur="paramInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column prop="edit" label="操作">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamBtn(scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParamBtn(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="attribute">
          <el-button :disabled="isBtnDisabled" @click="addParamBtn" type="primary">添加属性</el-button>
          <el-table stripe :data="attributesData" border style="width: 100%">
            <el-table-column type="expand" width="50" class="expand">
              <template v-slot="scope">
                <el-tag
                  class="paramClass"
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="paramInputVisible"
                  v-model="paramInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="paramInputConfirm(scope.row)"
                  @blur="paramInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column prop="edit" label="操作">
              <template v-slot="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamBtn(scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParamBtn(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="paramTitle"
      :visible.sync="dialogParamVisible"
      width="50%"
      class="catedialog"
      @closed="resetParam"
    >
      <el-form :model="paramForm" :rules="paramRules" ref="paramForm" label-width="100px">
        <el-form-item :label="addname" prop="attr_name">
          <el-input v-model="paramForm.attr_name" :autofocus="true"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogParamVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParam">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      params: [], // 级联选择器的数据
      goodsCateData: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeCate: 'params',
      // 分类id
      cateId: 0,
      // 属性Id
      attrId: 0,
      // 动态参数列表
      paramsData: [],
      attributesData: [],
      // 控制弹窗显示隐藏
      dialogParamVisible: false,
      // 空调弹窗是添加还是编辑
      dialogType: '',
      // 添加属性或参数的tag
      paramInputVisible: false,
      // 属性值
      paramInputValue: '',
      paramForm: {
        attr_name: '',
        attr_sel: 'many' // 默认动态参数
      },
      paramRules: {
        attr_name: [
          { required: true, message: '该字段不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCatesAll()
  },
  methods: {
    changeGoodsCate() {
      if (this.params.length !== 3) {
        this.params = []
        this.attributesData = []
        this.paramsData = []
        return
      }
      this.cateId = Array.from(this.params)[this.params.length - 1]
      if (this.activeCate === 'params') {
        this.getParams()
      } else {
        this.getAttribute()
      }
    },
    // 获取商品分类列表，渲染下拉列表
    async getCatesAll() {
      const { data: res } = await this.$axios.get('categories', {
        params: { type: 3 }
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.goodsCateData = res.data
    },
    // 获取动态参数
    async getParams() {
      if (this.cateId === 0) return this.$message.error('请选择商品分类')
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: 'many' }
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      res.data.forEach(item => {
        if (item.attr_vals.length === 0) {
          item.attr_vals = []
          return
        }
        item.attr_vals = item.attr_vals.split(' ')
      })
      this.paramsData = res.data
    },
    // 获取静态属性
    async getAttribute() {
      if (this.cateId === 0) return this.$message.error('请选择商品分类')
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: 'only' }
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      res.data.forEach(item => {
        if (item.attr_vals.length === 0) {
          item.attr_vals = []
          return
        }
        item.attr_vals = item.attr_vals.split(' ')
      })
      this.attributesData = res.data
    },
    // tab切换事件
    tabParams(tab, event) {
      if (this.params.length !== 3) return
      // console.log(tab.paneName)
      if (tab.paneName === 'params') {
        this.paramForm.attr_sel = 'many'
        // 动态参数
        this.getParams()
      } else {
        this.paramForm.attr_sel = 'only'
        // 静态属性
        this.getAttribute()
      }
    },
    // 操作tag
    showInput() {
      this.paramInputVisible = true
      // 获取焦点:$refs.input 中的input 是内置对象
      this.$nextTick(() => {
        // 要在结构更新完成后获取焦点!!!!
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    async paramInputConfirm(row) {
      // 当没输入内容，是空格时，清空
      if (this.paramInputValue.trim().length === 0) {
        this.paramInputValue = ''
        this.paramInputVisible = false
        return
      }
      // 将输入内容添加到attr_vals 数组中
      row.attr_vals.push(this.paramInputValue.trim())
      // 输入内容，提交保存
      const { data: res } = await this.$axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      // 没输入可空格时也清空
      this.paramInputValue = ''
      this.paramInputVisible = false
    },
    // 添加动态参数弹窗
    addParamBtn() {
      this.paramForm.attr_name = ''
      this.dialogType = 'add' // 此时是添加弹窗
      this.dialogParamVisible = true
    },
    // 添加/修改
    addParam() {
      this.$refs.paramForm.validate(async valid => {
        if (!valid) return this.$message.error('字段不能为空')
        if (this.dialogType === 'add') {
          console.log('add')
          const { data: res } = await this.$axios.post(
            `categories/${this.cateId}/attributes`,
            this.paramForm
          )
          if (res.meta.status !== 201) return this.$message.error('添加失败')
          if (this.activeCate === 'params') {
            // this.paramForm.attr_sel = 'many'
            this.getParams()
          } else {
            // this.paramForm.attr_sel = 'only'
            this.getAttribute()
          }
          this.$message.success('添加成功')
        } else {
          // 修改
          // console.log('edit')
          const { data: res } = await this.$axios.put(
            `categories/${this.cateId}/attributes/${this.attrId}`,
            this.paramForm
          )
          console.log(res)
          if (res.meta.status !== 200) return this.$message.error('更新失败')
          if (this.activeCate === 'params') {
            this.getParams()
          } else {
            this.getAttribute()
          }
          this.$message.success('更新成功')
        }
        this.dialogParamVisible = false
      })
    },
    resetParam() {
      this.$refs.paramForm.resetFields()
    },
    // 编辑
    async editParamBtn(param) {
      // console.log(param)

      // 点击编辑按钮获取当前参数
      // 编辑动态参数

      // 分类id:this.cateId
      // 属性id
      this.dialogType = 'edit' // 弹窗为编辑弹窗
      this.attrId = param.attr_id
      const { data: res } = await this.$axios.get(
        `categories/${this.cateId}/attributes/${this.attrId}`,
        {
          params: { attr_sel: this.paramForm.attr_sel }
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.paramForm.attr_name = res.data.attr_name
      this.dialogParamVisible = true
    },
    // 删除
    delParamBtn(p) {
      let attId = p.attr_id
      this.$confirm('此操作将永久删除该子弹, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$axios.delete(
            `categories/${this.cateId}/attributes/${attId}`
          )
          console.log(res)

          if (res.meta.status !== 200) return this.$message.error('删除失败')
          if (this.activeCate === 'params') {
            this.getParams()
          } else {
            this.getAttribute()
          }
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  },
  computed: {
    isBtnDisabled() {
      if (this.params.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 弹窗标题
    // paramTitle: '',
    paramTitle() {
      if (this.activeCate === 'params' && this.dialogType === 'add')
        return '添加动态参数'
      if (this.activeCate === 'params' && this.dialogType === 'edit')
        return '修改动态参数'
      if (this.activeCate === 'attribute' && this.dialogType === 'add')
        return '添加静态属性'
      if (this.activeCate === 'attribute' && this.dialogType === 'edit')
        return '修改静态属性'
    },
    // 添加的字段名
    addname() {
      if (this.activeCate === 'params') return '动态参数'
      if (this.activeCate === 'attribute') return '静态属性'
    }
  },
  // 监听计算属性paramTitle 判断是编辑还是添加
  watch: {
    paramTitle: {
      handler: function(newval, oldval) {}
    }
  }
}
</script>

<style lang='less' scoped>
.warning,
.params {
  margin: 10px 0;
}
.el-input {
  width: 80px;
}
.paramClass {
  margin: 10px;
}
</style>
